package logic

import (
	"context"
	"fmt"
	"time"
	"zhifubao/model/cache"
	"zhifubao/model/mysql"
	"zhifubao/pkg"

	"zhifubao/zhifubaorpc/internal/svc"
	"zhifubao/zhifubaorpc/zhifubaorpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterLogic) Register(in *zhifubaorpc.RegisterRequest) (*zhifubaorpc.RegisterResponse, error) {
	// todo: add your logic here and delete this line
	var finduser mysql.User
	mysql.DB.Debug().Where("account=?", in.Account).Find(&finduser)
	if finduser.ID != 0 {
		return nil, fmt.Errorf("该用户已被注册 请去登录")
	}
	result, _ := cache.Rdb.Get(l.ctx, "SendSms"+in.Account).Result()
	if result != in.SendCode {
		return nil, fmt.Errorf("验证码不匹配,请重新输入")
	}
	cache.Rdb.Set(l.ctx, "SendSms"+in.Account, result, time.Minute*3)
	users := mysql.User{
		Account:  in.Account,
		Password: pkg.Md5("123456"),
	}
	mysql.DB.Debug().Create(&users)
	return &zhifubaorpc.RegisterResponse{
		Id: int64(users.ID),
	}, nil
}
